<template>
  <ul class="list" v-loading="fileLoading" :class="{ closable }">
    <li class="item" v-for="file in fileList" :key="file.id">
      <i class="btn-close el-icon-close pointer" @click="onClose(file)" v-if="closable" />
      <div class="icon">
        <i class="el-icon-picture-outline" v-if="pictureExtNames.includes(file.type)" />
        <i class="el-icon-document" v-else />
      </div>
      <span class="name ellipsis2 pointer" :title="file.fileName" @click="onDownload(file)">{{ file.fileName }}</span>
    </li>
  </ul>
</template>
<script>
import { pictureExtNames } from '@/utils'
import { downloadFile } from '@/api/common'
export default {
  name: 'SysFilesDisplay',
  props: {
    fileList: { type: Array, default: () => [] },
    closable: Boolean
  },
  data() {
    return {
      pictureExtNames,
      fileLoading: false
    }
  },
  methods: {
    onClose(file) {
      this.$emit('close', file)
    },
    async onDownload(file) {
      this.fileLoading = true
      const res = await downloadFile(file.id).catch(() => false)
      this.fileLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = file.fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    }
  }
}
</script>
<style lang="scss" scoped>
.list {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  padding-left: unset;
  margin: unset;
}
.closable .item:hover {
  border-color: #e6ebf5;
  .btn-close {
    display: block;
  }
}
.item {
  position: relative;
  width: 33.33%;
  border: 1px solid transparent;
  box-sizing: border-box;
  padding: 10px 20px 10px 36px;
  border-radius: 4px;
}
.btn-close {
  position: absolute;
  top: 0;
  right: 0;
  padding: 5px;
  display: none;
  &:hover {
    color: #409eff;
  }
}
.icon {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 16px;
}
.name:hover {
  color: #409eff;
  text-decoration: underline;
}
</style>
